// 编译环境：Visual Studio + EasyX
// 下载 EasyX并安装：https://easyx.cn/easyx

#include <graphics.h>
#include <math.h>
#include <time.h>
#include <conio.h>          // kbhit, getch
#define PI 3.14159265358979323846
#define WIDTH      800
#define HEIGHT     600
#define HEART_SIZE 12.0            // 基础放大倍数
#define PARTICLE_N 600             // 粒子数量

typedef struct {
    double x, y;   // 当前坐标
    double vx, vy; // 速度
    int    life;   // 剩余帧数
    int    maxLife;
} Particle;

Particle pts[PARTICLE_N];

// 心脏公式
void heartFormula(double t, double& x, double& y) {
    x = 16 * sin(t) * sin(t) * sin(t);
    y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t));
}

// 随机 double
double randf(double min, double max) {
    return min + (max - min) * rand() / RAND_MAX;
}

// 初始化粒子：沿爱心轮廓均匀采样
void initParticles() {
    for (int i = 0; i < PARTICLE_N; ++i) {
        double t = randf(0, 2 * PI);
        double x, y;
        heartFormula(t, x, y);
        pts[i].x = WIDTH / 2 + x * HEART_SIZE;
        pts[i].y = HEIGHT / 2 + y * HEART_SIZE;

        // 径向爆炸速度
        double len = sqrt(x * x + y * y);
        pts[i].vx = x / len * randf(1, 4);
        pts[i].vy = y / len * randf(1, 4);
        pts[i].maxLife = pts[i].life =(int)randf(40, 90);
    }
}

// 主循环
int main() {
    initgraph(WIDTH, HEIGHT);
    setbkcolor(BLACK);
    BeginBatchDraw();
    srand((unsigned)time(NULL));

    initParticles();
    double scale = 1.0;
    bool growing = true;

    while (true) {
        while (_kbhit()) {
            char c = _getch();
            if (c == 27) return 0;      // ESC 退出
            if (c == ' ') initParticles(); // 空格重爆
        }

        // 脉动缩放
        if (growing) scale += 0.015;
        else scale -= 0.015;
        if (scale > 1.15) growing = false;
        if (scale < 0.85) growing = true;

        // 清屏（黑色半透明覆盖实现拖尾）
        setfillcolor(RGB(2, 0, 0));
        solidrectangle(0, 0, WIDTH, HEIGHT);

        // 更新并绘制粒子
        for (int i = 0; i < PARTICLE_N; ++i) {
            pts[i].x += pts[i].vx;
            pts[i].y += pts[i].vy;
            pts[i].vy += 0.04;          // 重力
            pts[i].life--;

            int alpha = pts[i].life * 255 / pts[i].maxLife;
            int r = 255, g = alpha / 3, b = alpha / 4;
            solidcircle((int)pts[i].x, (int)pts[i].y,
                (int)(scale * 2.5 * pts[i].life / pts[i].maxLife));
            setfillcolor(RGB(r, g, b));
        }

        // 中心实心爱心（同步脉动）
        setfillcolor(RGB(255, 0, 0));
        for (double t = 0; t <= 2 * PI; t += 0.02) {
            double x, y;
            heartFormula(t, x, y);
            x = WIDTH / 2 + x * HEART_SIZE * scale;
            y = HEIGHT / 2 + y * HEART_SIZE * scale;
            solidcircle((int)x, (int)y, (int)(3 * scale));
        }

        FlushBatchDraw();
        Sleep(16);   // 约 60 FPS
    }

    EndBatchDraw();
    closegraph();
    return 0;
}